package com.cuz.hot100;

public class Q19removeNthFromEnd {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (n < 0 || head == null) {
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode slowPre = new ListNode();
        slowPre.next = head;
        while (n > 0 && fast != null) {
            fast = fast.next;
            n--;
        }
        if (fast==null){
            return slow.next;
        }
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
            slowPre = slowPre.next;
        }
        slowPre.next = slow.next;
        return head;
    }


    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        ListNode listNode = removeNthFromEnd(node1, 4);

        while (listNode!=null){
            System.out.println(listNode.val);
            listNode=listNode.next;
        }
    }
}
